#!/usr/bin/env python3

import pygame
import os
import pdb
import logging
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
import bezier_curve_algorithm as ba

# 配置log输出的级别和格式
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 贝塞尔曲线的控制点
p0 = ba.Point(200,300)#起点
p1 = ba.Point(300,100) #控制点
p2 = ba.Point(600, 90) #控制点
p3 = ba.Point(700 ,300) #终点

control_points = [p0, p1, p2, p3]
#control_points = [p0, p1, p3]

# 初始化 Pygame 和 OpenGL
pygame.init()
display = (800, 600)
pygame.display.set_mode(display, DOUBLEBUF|OPENGL)

glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluOrtho2D(0, display[0], 0, display[1])

glMatrixMode(GL_MODELVIEW)
glLoadIdentity()

# 主循环
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

    # 绘制控制点
    glColor3f(1, 0, 0)
    glPointSize(5)
    glBegin(GL_POINTS)
    for point in control_points:
        glVertex2f(point.x, point.y)
    glEnd()

    # 绘制贝塞尔曲线
    glColor3f(0, 1, 0)
    glBegin(GL_LINE_STRIP)

    max_point_num = 30
    ctrl_points_num = len (control_points)
    bezier_curve = []
    if 3 == ctrl_points_num:
        bezier_curve = ba.quadratic_bezier_curve(control_points[0], control_points[1], control_points[2], max_point_num)
    elif 4 == ctrl_points_num:
        bezier_curve = ba.cubic_bezier_curve(control_points[0], control_points[1], control_points[2], control_points[3], max_point_num)

    for pos in bezier_curve:    
        glVertex2f(pos.x, pos.y)

    glEnd()

    pygame.display.flip()
    pygame.time.wait(10)
